// 05.03.12 - Matthew Brews - Original Creation.

#include "weapon.h"

CWeapon::CWeapon(const int nClipSize,
                 const string &szWeaponName,
                 const ENTITY_ID &nId) : 
    m_nClipSize(nClipSize),
    CMovableEntity(szWeaponName, nId, 0.0f, 0.0f, 0.0f),
    m_fWeaponAttackDelay(100.0f), // Default to 200ms delay
    m_nAmmoCount(0),
    m_nClipCount(nClipSize)
{
    CMesh *pMesh(CMeshContainer::getInstance()->getMesh(szWeaponName));
    if (pMesh == nullptr)
    {
        pMesh = CMeshContainer::getInstance()->addMesh(szWeaponName);
        pMesh->loadMesh(CDeviceManager::getInstance()->getDevice(), 
            (string("models/") + szWeaponName + ".x").c_str());
    }

    CDisplayable *pDisplayable(
        CDisplayableContainer::getInstance()->createDisplayable(pMesh));

    setDisplayable(pDisplayable);

    setTimeNextFire(CTimer());
    setTimeLastFired(CTimer());
}

CWeapon::~CWeapon()
{
}

bool CWeapon::fire()
{
    if (getTimeNextFire().getTimeDifference() >= 0.0)
    {
        // Attack delay over
        if (m_nClipCount > 0 || m_nAmmoCount > 0)
        {
            // We have at least some ammo
            --m_nClipCount;
            if (m_nClipCount <= 0)
            {
                // Reload
                int nSize(min(m_nClipSize, m_nAmmoCount));
                m_nAmmoCount -= nSize;
                m_nClipCount += nSize;
            }

            setTimeNextFire(CTimer() +  getWeaponAttackDelay());
            setTimeLastFired(CTimer());

            return true;
        }
    }
    return false;
}

void CWeapon::setWeaponName(string name)
{
    m_szWeaponName = name;
}

string CWeapon::getWeaponName() const
{
    return m_szWeaponName;
}

int CWeapon::getClipCount() const
{
    return m_nClipCount;
}

void CWeapon::setClipCount(int nCount)
{
    m_nClipCount = nCount;
}

int CWeapon::getAmmoCount() const
{
    return m_nAmmoCount;
}

void CWeapon::setAmmoCount(int nCount)
{
    m_nAmmoCount = nCount;
}

CTimer CWeapon::getTimeLastFired() const
{
    return m_timeLastFired;
}

CTimer CWeapon::getTimeNextFire() const
{
    return m_timeNextFire;
}

void CWeapon::setTimeNextFire(const CTimer &timeFire)
{
    m_timeNextFire = timeFire;
}

void CWeapon::setTimeLastFired(const CTimer &timeFire)
{
    m_timeLastFired = timeFire;
}

float CWeapon::getWeaponAttackDelay() const
{
    return m_fWeaponAttackDelay;
}

void CWeapon::setWeaponAttackDelay(float fWeaponAttackDelay)
{
    m_fWeaponAttackDelay = fWeaponAttackDelay;
}